#!/bin/bash
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


_tryit() {
    coverage run --parallel-mode --module taihe.cli.tryit "$@"
}

run-core-tests() {
    for test_dir in ../test/rgb ../test/object; do
        echo "Testing: $test_dir"
        _tryit test -u cpp $test_dir
    done
}

run-ani-tests() {
    echo "Running ANI tests..."

    cd ..
    if [ -d "build" ]; then
        echo "Build directory found. Skipping CMake configuration."
    else
        echo "Build directory not found. Configuring with CMake."
        if [ -n "$1" ]; then
            echo "Using custom PANDA_HOME: $1"
            cmake -B build -GNinja -DENABLE_COVERAGE=ON -DPANDA_HOME="$1"
        else
            echo "No PANDA_HOME provided"
            cmake -B build -GNinja -DENABLE_COVERAGE=ON
        fi
    fi
    cmake --build build --verbose
    cd compiler
}

run-cmake-test() {
    test_dir=../test/cmake_test
    echo "Testing: $test_dir"
    _tryit generate -u sts $test_dir --cmake
    cd ../test/cmake_test/
    cmake -B build/generated \
        -D EXTERNAL_INCLUDE=$(realpath ../../.panda_vm/package/ohos_arm64/include/plugins/ets/runtime/ani)
    cmake --build build/generated
    cd ../..
    cd compiler
}

run-pytest() {
    echo "Running pytest..."
    coverage run --parallel-mode --module pytest
}

source "$(dirname "$0")/common_lib.sh"
init_py_env

# Add trap to ensure coverage is reported even if script exits early
trap "coverage combine && coverage report" EXIT

run-pytest
if [ $# -eq 0 ]; then
    echo "No PANDA_HOME provided, running without -DPANDA_HOME"
    run-ani-tests ""
else
    run-ani-tests $1
fi

# The coverage report will be generated by the EXIT trap
echo "Generating coverage report..."
